<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\Payment;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;
use Inertia\Response;

class PaymentController extends Controller
{
    /**
     * 显示支付页面
     */
    public function show(string $orderNumber): Response|RedirectResponse
    {
        // 根据订单号查找订单
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        // 检查订单是否属于当前用户
        if ($order->user_id !== auth()->id()) {
            return redirect()->route('orders.index')
                ->with('error', '无权访问该订单');
        }

        // 检查订单是否可以支付
        if (!$order->canPay()) {
            return redirect()->route('order.show', $order->order_number)
                ->with('error', '订单状态不允许支付');
        }

        // 获取或创建支付记录
        $payment = $order->payments()
            ->where('status', Payment::STATUS_PENDING)
            ->first();

        if (!$payment) {
            $payment = Payment::createForOrder($order, Payment::METHOD_MOCK, [
                'expires_at' => now()->addMinutes(30),
            ]);
        }

        return Inertia::render('Shop/Payment/Show', [
            'order' => $order->load(['items.product', 'user', 'userCoupon.coupon']),
            'payment' => $payment,
        ]);
    }

    /**
     * 处理支付请求
     */
    public function pay(Request $request, string $orderNumber)
    {
        // 根据订单号查找订单
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        $request->validate([
            'payment_method' => 'required|string|in:alipay,wechat,mock',
        ]);

        // 检查订单是否属于当前用户
        if ($order->user_id !== auth()->id()) {
            return response()->json([
                'success' => false,
                'message' => '无权访问该订单',
            ], 403);
        }

        // 检查订单是否可以支付
        if (!$order->canPay()) {
            return response()->json([
                'success' => false,
                'message' => '订单状态不允许支付',
            ], 400);
        }

        try {
            $paymentMethod = $request->input('payment_method');
            
            // 更新订单的支付方式
            $order->update(['payment_method' => $paymentMethod]);
            
            // 查找现有的支付记录（任何状态），如果没有则创建新的
            $payment = $order->payments()
                ->where('payment_method', $paymentMethod)
                ->first();
                
            if (!$payment) {
                // 创建新的支付记录
                $payment = Payment::createForOrder($order, $paymentMethod, [
                    'expires_at' => now()->addMinutes(30),
                ]);
            } else {
                // 更新现有支付记录的状态和过期时间
                $payment->update([
                    'status' => Payment::STATUS_PENDING,
                    'expires_at' => now()->addMinutes(30),
                    'updated_at' => now(),
                ]);
            }

            // 根据支付方式处理
            switch ($paymentMethod) {
                case Payment::METHOD_MOCK:
                    return $this->handleMockPayment($payment);
                    
                case Payment::METHOD_ALIPAY:
                    return $this->handleAlipayPayment($payment);
                    
                case Payment::METHOD_WECHAT:
                    return $this->handleWechatPayment($payment);
                    
                default:
                    return response()->json([
                        'success' => false,
                        'message' => '不支持的支付方式',
                    ], 400);
            }
        } catch (\Exception $e) {
            Log::error('支付处理失败', [
                'order_id' => $order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'success' => false,
                'message' => '支付处理失败，请重试',
            ], 500);
        }
    }

    /**
     * 处理模拟支付
     */
    private function handleMockPayment(Payment $payment)
    {
        try {
            \Log::info('开始处理模拟支付', [
                'payment_id' => $payment->id,
                'order_id' => $payment->order_id,
            ]);
            
            $result = $payment->processMockPayment();
            
            \Log::info('模拟支付处理结果', [
                'payment_id' => $payment->id,
                'result' => $result,
            ]);
            
            if ($result['success']) {
                // 支付成功，更新订单状态
                \Log::info('开始更新订单状态', [
                    'payment_id' => $payment->id,
                    'order_id' => $payment->order_id,
                ]);
                
                $payment->order->markAsPaid();
                
                \Log::info('订单状态更新完成', [
                    'payment_id' => $payment->id,
                    'order_id' => $payment->order_id,
                ]);
                
                // 返回 JSON 响应，前端使用 Inertia.js 跳转
                return response()->json([
                    'success' => true,
                    'message' => '支付成功',
                    'order_number' => $payment->order->order_number,
                ]);
            } else {
                // 支付失败，不更新订单状态，只返回错误信息
                \Log::info('支付失败，不更新订单状态', [
                    'payment_id' => $payment->id,
                    'order_id' => $payment->order_id,
                    'error' => $result['message'],
                ]);
                
                return response()->json([
                    'success' => false,
                    'message' => $result['message'],
                ], 400);
            }
        } catch (\Exception $e) {
            \Log::error('模拟支付处理异常', [
                'payment_id' => $payment->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '模拟支付处理失败',
            ], 500);
        }
    }

    /**
     * 处理支付宝支付（预留接口）
     */
    private function handleAlipayPayment(Payment $payment): JsonResponse
    {
        // TODO: 实现真实的支付宝支付
        // 这里返回模拟数据，实际项目中需要调用支付宝 API
        
        return response()->json([
            'success' => false,
            'message' => '支付宝支付暂未开通，请使用模拟支付',
        ], 400);
    }

    /**
     * 处理微信支付（预留接口）
     */
    private function handleWechatPayment(Payment $payment): JsonResponse
    {
        // TODO: 实现真实的微信支付
        // 这里返回模拟数据，实际项目中需要调用微信支付 API
        
        return response()->json([
            'success' => false,
            'message' => '微信支付暂未开通，请使用模拟支付',
        ], 400);
    }

    /**
     * 支付回调处理（支付宝）
     */
    public function alipayCallback(Request $request): JsonResponse
    {
        // TODO: 实现支付宝回调处理
        Log::info('支付宝回调', $request->all());
        
        return response()->json(['success' => true]);
    }

    /**
     * 支付回调处理（微信）
     */
    public function wechatCallback(Request $request): JsonResponse
    {
        // TODO: 实现微信支付回调处理
        Log::info('微信支付回调', $request->all());
        
        return response()->json(['success' => true]);
    }

    /**
     * 查询支付状态
     */
    public function status(string $orderNumber): JsonResponse
    {
        // 根据订单号查找订单
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        // 检查订单是否属于当前用户
        if ($order->user_id !== auth()->id()) {
            return response()->json([
                'success' => false,
                'message' => '无权访问该订单',
            ], 403);
        }

        $payment = $order->payments()->latest()->first();
        
        if (!$payment) {
            return response()->json([
                'success' => false,
                'message' => '未找到支付记录',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'payment' => [
                'id' => $payment->id,
                'status' => $payment->status,
                'status_name' => $payment->status_name,
                'payment_method' => $payment->payment_method,
                'payment_method_name' => $payment->payment_method_name,
                'amount' => $payment->amount,
                'paid_at' => $payment->paid_at,
                'expires_at' => $payment->expires_at,
                'is_expired' => $payment->isExpired(),
            ],
        ]);
    }

    /**
     * 取消支付
     */
    public function cancel(string $orderNumber): JsonResponse
    {
        // 根据订单号查找订单
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        // 检查订单是否属于当前用户
        if ($order->user_id !== auth()->id()) {
            return response()->json([
                'success' => false,
                'message' => '无权访问该订单',
            ], 403);
        }

        $payment = $order->payments()
            ->where('status', Payment::STATUS_PENDING)
            ->first();

        if (!$payment) {
            return response()->json([
                'success' => false,
                'message' => '未找到待支付的记录',
            ], 404);
        }

        $payment->update(['status' => Payment::STATUS_CANCELLED]);

        return response()->json([
            'success' => true,
            'message' => '支付已取消',
        ]);
    }
}